package com.example.wotu;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.nfc.Tag;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity
        implements
        FragBookFind.OnFragmentInteractionListener,
        FragBookList.OnFragmentInteractionListener,
        FragWLBook.OnFragmentInteractionListener,
        FragWLOpenBook.OnFragmentInteractionListener,
        FragWLLookBook.OnFragmentInteractionListener,
        FragBook.OnFragmentInteractionListener,
        FragBookml.OnFragmentInteractionListener,
        FragBookCont.OnFragmentInteractionListener,
        Individual.OnFragmentInteractionListener,
        FragBookDR.OnFragmentInteractionListener{
    /*使用Toolbar需要改三个地方，方可使用
     * 1.修改对应的视图java层的引用文件为：import androidx.appcompat.widget.Toolbar;
     * 2.修改 AndroidManifest.xml 里面的 android:theme="@style/AppTheme" 配置为：android:theme="@style/Theme.AppCompat.NoActionBar"
     * 3.在 onCreate 里获取Toolbar 的id后，要将它添加设置为：setSupportActionBar(toolbar);
     * 4.前三步完成后就可以了。
     * 注意一点：style.mxl 的样式 name 对应于 AndroidManifest.xml 的 android:theme。意思就是这里是什么名字，style 的 name 就是什么名字
     *
     * 5.修改 Toolbar 加或减样式，需在 res new 一个 Android Resource Directory 添加为：menu(随命名)
     * 6.然后在 new 一个 Menu resource File 选为 menu 最后名称，就可以在里面添加样式。
     *
     * 7.子线程已经用了两种为：①AsyncTask<S,I,S>; ② Thread;
     */

    private final static String PIC_URL = "https://ww2.sinaimg.cn/large/7a8aed7bgw1evshgr5z3oj20hs0qo0vq.jpg";
    private final static String HTML_URL = "https://www.baidu.com";
    private final static String HTML_FL_URL = "https://www.qinqinxsw.com/book/121671.html";
    private final static String HTML_BQG_URL = "https://www.xbiquge.la/xiaoshuodaquan/";
    private Bitmap bitmap;
    private String urlStringPIC;

    private Toolbar toolbar;
    private ImageView imageView;
    private TextView textView;
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    private Fragment fragbook;
    private FrameLayout fragaction;

    private MyBRReceiver myReceiver;

    public int NOTWK = 100,userid;
    private long exiT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        userid = getIntent().getExtras().getInt("useid");
        setFindView();
        OnBun(0);

        myReceiver = new MyBRReceiver();
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(myReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除广播
        unregisterReceiver(myReceiver);
    }

    //实现OnFragmentInteractionListener接口中的函数
    public void onFragmentInteraction(Uri uri){

    }
    public void onGoBack(int f){
        if(f == 102){
            FrameLayout WLcont = findViewById(R.id.WLcontext);
            LinearLayout wlFG = findViewById(R.id.wlFG);
            WLcont.setVisibility(View.GONE);
            wlFG.setVisibility(View.VISIBLE);
        }
        else if(f == 104){
            FrameLayout btlookb = findViewById(R.id.btlookb);
            LinearLayout shujll = findViewById(R.id.shujll);
            btlookb.setVisibility(View.GONE);
            shujll.setVisibility(View.VISIBLE);
        }
    }
    public void onNOT_WK(int wk){
        NOTWK = wk;
    }
    public int usei(){
        return userid;
    }

    //1.获取组件；2.隐藏组件；3.返回创建
    private void setFindView(){
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
//        toolbar.setLogo(R.mipmap.ic_launcher_round);

        imageView = findViewById(R.id.imageView);
        textView = findViewById(R.id.textView);

        mViewPager = findViewById(R.id.viewpage);
        fragaction = (FrameLayout)findViewById(R.id.fragaction);
    }
    private void setVis(){
        imageView.setVisibility(View.GONE);
        textView.setVisibility(View.GONE);
        mViewPager.setVisibility(View.GONE);
        fragaction.setVisibility(View.GONE);
    }

    //引用设置按钮所导入的xml
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //会默认给3个点的图标
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    private void OnBun(int b){
        fragaction.setVisibility(View.VISIBLE);
        if(b == 0){
            fragbook = new FragBook();
        }else if(b == 1){
            fragbook = new Individual();
            Bundle bu = new Bundle();
            bu.putInt("us",userid);

        }
        getSupportFragmentManager().beginTransaction().replace(R.id.fragaction,fragbook).commitAllowingStateLoss();
    }
    //Toolbar 的 action按钮的事件响应
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        setVis();
        switch (item.getItemId())
        {
            case R.id.tool_logo:
                OnBun(0);
                break;
            case R.id.tool_xs:
                //先建 ViewPager 的自定义适配器，再建各 Fragment 添加到 ViewPager 生成循环
                mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
                ArrayList<Fragment> datas = new ArrayList<>();
                datas.add(new FragBookList());
                datas.add(new FragWLBook());
                mSectionsPagerAdapter.setData(datas);
                mViewPager.setVisibility(View.VISIBLE);
                mViewPager.setAdapter(mSectionsPagerAdapter);
                break;
            case R.id.tool_ylpic:
                Toast.makeText(MainActivity.this, "预留图加载", Toast.LENGTH_SHORT).show();
                imageView.setVisibility(View.VISIBLE);
                urlStringPIC = PIC_URL;
                new PICnextWork().execute();
                break;
            case R.id.tool_ylxml:
                Toast.makeText(MainActivity.this, "预留xml加载", Toast.LENGTH_SHORT).show();
                textView.setVisibility(View.VISIBLE);
                new NextBulE().execute(HTML_URL);
                break;
            case R.id.tool_sett:
                OnBun(1);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //网络图片处理（暂时发现 HttpURLConnection 部分只能放在子线程所调用，其它地方报错）
    private byte[] getImage(String path){
        try {
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            connection.setRequestMethod("GET");
            connection.connect();

            if (connection.getResponseCode() != 200) {
                throw new RuntimeException("请求url失败");
            }
            InputStream inputStream = connection.getInputStream();
            //处理流
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = inputStream.read(buffer)) != -1)
            {
                outStream.write(buffer,0,len);
            }
            byte[] bt = outStream.toByteArray();
            return bt;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    class PICnextWork extends AsyncTask<byte[],Integer,byte[]> {
        @Override
        protected byte[] doInBackground(byte[]... bytes) {
            byte[] result = getImage(urlStringPIC);
            return result;
        }

        @Override
        protected void onPostExecute(byte[] bytes) {
            super.onPostExecute(bytes);
            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            ImageView img = findViewById(R.id.imageView);
            img.setImageBitmap(bitmap);
        }
    }
    //网络链接（注意：网络连接等处理都要在子线程，而且在线程里面不能处理UI，否则闪退）
    private String requesData(String urlString) {
        try {
            //1.获取链接地址；2.打开网络服务；3.设置连接超时时间，读取超时时间；4.设置提交方式；5.开启
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(5000);
            connection.setRequestMethod("GET");
            connection.connect();

            //1.返回结果编码/200 ok；2.我们想要的流
            if (connection.getResponseCode() != 200) {
                throw new RuntimeException("请求url失败");
            }
            InputStream inputStream = connection.getInputStream();

            //处理转换流
            Reader reader = new InputStreamReader(inputStream, "UTF-8");
            char[] buffer = new char[2048];
            reader.read(buffer);
            String content = new String(buffer);
            connection.disconnect();
            return content;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    //安卓特有的异步处理类：AsyncTask<类型，进度条/Integer，返回值>
    class NextBulE extends AsyncTask<String,Integer,String>{

        //之前：在后台之前执行的主线程
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //UI的加载：就是转圈
        }

        //后台运行
        @Override
        protected String doInBackground(String[] objects) {     //因为他是可变形数组
            String result = requesData(objects[0]);
            return result;
        }

        //之后：后台执行完了回到主线程，result 就来到这里了
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            textView.setText(result);
        }

        //取消
        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        //更新
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }
    }

    //退出
    @Override
    public void onBackPressed() {
        //100：当前父栏
        if(NOTWK == 100 || NOTWK == 101){
            if((System.currentTimeMillis()-exiT)>2000){
                Toast.makeText(MainActivity.this,"是否退出红墨？",Toast.LENGTH_SHORT).show();
                exiT=System.currentTimeMillis();
            }else{
                Toast.makeText(MainActivity.this,"已退出",Toast.LENGTH_SHORT).show();
                finishAffinity();
            }
        }
        else if(NOTWK == 102 || NOTWK == 104){
            onGoBack(NOTWK);
            NOTWK = 101;
        }
        else if(NOTWK == 103){
            FrameLayout looks = findViewById(R.id.LOOKS);
            LinearLayout openb = findViewById(R.id.openbook);
            looks.setVisibility(View.GONE);
            openb.setVisibility(View.VISIBLE);
            NOTWK = 102;
        }
        else if(NOTWK == 105){
            FrameLayout ContB = findViewById(R.id.ContB);
            ContB.setVisibility(View.GONE);
            LinearLayout mllayout = findViewById(R.id.mllayout);
            mllayout.setVisibility(View.GONE);
            LinearLayout shuj = (LinearLayout)findViewById(R.id.shuj);
            shuj.setVisibility(View.VISIBLE);
            NOTWK = 101;
        }
        else if(NOTWK == 106){
            FrameLayout ContB = findViewById(R.id.ContB);
            ContB.setVisibility(View.GONE);
            LinearLayout mllayout = findViewById(R.id.mllayout);
            mllayout.setVisibility(View.VISIBLE);
            NOTWK = 105;
        }
        else if(NOTWK == 107){
            LinearLayout LA = findViewById(R.id.LA);
            RelativeLayout LB = findViewById(R.id.LB);
            LA.setVisibility(View.GONE);
            LB.setVisibility(View.VISIBLE);
            NOTWK = 104;
        }
        else if(NOTWK == 108){
            LinearLayout shu = (LinearLayout)findViewById(R.id.shuj);
            LinearLayout Insbook = (LinearLayout)findViewById(R.id.Insbook);
            Insbook.setVisibility(View.GONE);
            shu.setVisibility(View.VISIBLE);
            NOTWK = 101;
        }
        else if(NOTWK == 109){
            LinearLayout shu = (LinearLayout)findViewById(R.id.shuj);
            FrameLayout fragml = (FrameLayout)findViewById(R.id.fragml);
            fragml.setVisibility(View.GONE);
            shu.setVisibility(View.VISIBLE);
            //调用子碎片方法
            FragBook fbk = (FragBook)getSupportFragmentManager().findFragmentById(R.id.fragaction);
            fbk.getBookData();
            NOTWK = 101;
        }
    }
}